package com.zhiwei.service;

import com.zhiwei.configuration.SysConf;
import com.zhiwei.vo.ImagVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    SysConf sysConf;

    @Override
    public ImagVO upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        fileName = fileName.toLowerCase();
        if (!fileName.matches("^.+\\.(jpg|png|gif|jpeg|img|bmp)$")) {
            return null;
        }
//        通过宽度高度判断是否为图片
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            int height = image.getHeight();
            int width = image.getWidth();
            if (height == 0 || width == 0) {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
//        分目录存储
        String fileDir = sysConf.getFilePath() + "img/";
        File dirFile = new File(fileDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
//        生成文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String imageName = uuid + fileType;
        try {
            file.transferTo(new File(fileDir + imageName));
            //        封装imageVO对象

            return new ImagVO().setVirtualPath(fileDir + imageName)
                    .setFileName(imageName)
                    .setUrlPath("/img/" + imageName);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void deleteFile(String virtualPath) {
        new File(virtualPath).delete();
    }
}
